package com.own.component.store.core.controller;

import com.own.aop.login.LoginIgnore;
import com.own.component.common.base.controller.BaseController;
import com.own.component.common.model.R;
import com.own.component.common.model.ResultModel;
import com.own.component.store.core.exception.StoreException;
import com.own.component.store.core.util.base.RsaKeyUtil;
import com.own.constant.ConstantEnvironmentType;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;

/**
 * BaseStoreController
 *
 * @author chenxueli
 * @date 2023-06-26 20:00:00
 */
public class BaseStoreController extends BaseController {

    @Resource
    public RsaKeyUtil rsaKeyUtil;

    @LoginIgnore
    @Operation(summary = "获取RSA公钥")
    @GetMapping("/key/{sign}")
    public ResultModel<String> getPublicKey(
            @Parameter(description = "加密标识") @PathVariable String sign
    ) {
        if (sign.length() > 64) {
            throw new StoreException("加密标识长度不能超过64位");
        }
        var key = rsaKeyUtil.build(sign);
        return R.success(key.getPublicKey());
    }

    @LoginIgnore
    @Profile({ConstantEnvironmentType.DEV, ConstantEnvironmentType.LOCALHOST, ConstantEnvironmentType.TEST})
    @Operation(summary = "RSA加密内容")
    @GetMapping("/encrypt/{sign}")
    public ResultModel<String> getPublicKey(
            @Parameter(description = "加密标识") @PathVariable String sign,
            @Parameter(description = "待加密的内容") @RequestParam String content
    ) {
        if (sign.length() > 64) {
            throw new StoreException("加密标识长度不能超过64位");
        }
        if (content.length() > 512) {
            throw new StoreException("待加密的内容长度不能超过512位");
        }
        var text = rsaKeyUtil.encrypt(sign, content);
        return R.success(text);
    }

}
